<template>
  <ContentWrap>
    <el-form
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="100px"
      label-position="left"
    >
      <el-form-item label="客户">
        <el-select v-model="queryParams.tenantId" placeholder="请选择客户">
          <el-option
            v-for="item in customerOptions"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="时间区间" prop="times">
        <el-date-picker
          :clearable="false"
          v-model="queryParams.times"
          value-format="YYYY-MM-DD HH:mm:ss"
          type="daterange"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="">
        <el-button
          type="success"
          plain
          @click="handleExport"
          :loading="exportLoading"
          v-hasPermi="['call:stat:export']"
        >
          <Icon icon="ep:download" class="mr-5px" />
          导出
        </el-button>
        <el-button @click="handleQuery">
          <Icon icon="ep:search" class="mr-5px" />
          搜索
        </el-button>
        <el-button @click="resetQuery">
          <Icon icon="ep:refresh" class="mr-5px" />
          重置
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>
  <ContentWrap>
    <el-table
      v-loading="loading"
      :data="list"
      :stripe="true"
      @sort-change="sortChange"
      :show-overflow-tooltip="true"
      border
    >
      <el-table-column label="时间" align="center" prop="datetime" :sortable="true" />
      <el-table-column label="外呼总量" align="center" prop="totalCount" :sortable="true" />
      <el-table-column label="接通量" align="center" prop="successCount" :sortable="true" />
      <el-table-column label="接通率" align="center" prop="rate" :sortable="true">
        <template #default="scope">
          <span> {{ scope.row.rate }}% </span>
        </template>
      </el-table-column>
      <el-table-column label="通话时长" align="center" prop="callSecond" :sortable="true">
        <template #default="scope">
          <span>
            {{ convertSecondsToHMS(scope.row.callSecond) }}
          </span>
        </template>
      </el-table-column>
      <el-table-column
        label="计费分钟"
        align="center"
        prop="callMinute"
        :sortable="true"
      ></el-table-column>
      <el-table-column label="话费成本" align="center" prop="callCostPrice" :sortable="true">
        <template #default="scope">
          {{ scope.row.callCostPrice.toFixed(2) }}
        </template>
      </el-table-column>
      <el-table-column label="实际话费" align="center" prop="callSalePrice" :sortable="true">
        <template #default="scope">
          {{ scope.row.callSalePrice.toFixed(2) }}
        </template>
      </el-table-column>
      <el-table-column label="单日利润" align="center" prop="currentProfit" :sortable="true">
        <template #default="scope">
          {{ scope.row.currentProfit.toFixed(2) }}
        </template>
      </el-table-column>
      <el-table-column label="截至当日总利润" align="center" prop="totalProfit" :sortable="true">
        <template #default="scope">
          {{ scope.row.totalProfit.toFixed(2) }}
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center">
        <template #default="scope">
          <el-button v-if="scope.row.year" link type="primary" @click="showOwner(scope.row)">
            查看
          </el-button>
          <el-button v-if="scope.row.year" link type="primary" @click="exportOwner(scope.row)">
            导出
          </el-button>
        </template>
      </el-table-column>
    </el-table>
  </ContentWrap>
  <OwnerStat ref="ownerStatRef" />
</template>

<script setup>
import { convertSecondsToHMS } from '@/utils/formatTime'
import download from '@/utils/download'
import OwnerStat from '@/views/call/statistics/dataReport/OwnerStat.vue'
import * as proxyApi from '@/api/home/proxy.ts'

const queryParams = reactive({
  times: null,
  group: 'day',
  sortStr: '',
  sortFields: {},
  tenantId: ''
})
const loading = ref(false)
const list = ref([])

// 列表
const getList = async () => {
  try {
    if (Object.keys(queryParams.sortFields).length > 0) {
      queryParams.sortStr = JSON.stringify(queryParams.sortFields)
    }
    const data = await proxyApi.listByList(queryParams)
    list.value = data
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  getList()
}

const queryFormRef = ref(null)
/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  queryFormRef.sortFields = {}
  queryParams.times = getCurrentMonthRange()
  handleQuery()
}
/*导出*/
const exportLoading = ref(false)
const handleExport = async () => {
  try {
    // 发起导出
    exportLoading.value = true
    const data = await proxyApi.exportExcelByProxy(queryParams)
    download.excel(data, '数据报表.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}
const sortChange = (column) => {
  queryParams.sortFields[column.prop] = column.order == 'descending' ? 'desc' : 'asc'
  handleQuery()
}

const ownerStatRef = ref(null)
const showOwner = (row) => {
  let times
  if (queryParams.group == 'day') {
    times = [row.datetime + ' 00:00:00', row.datetime + ' 23:59:59']
  } else if (queryParams.group == 'month') {
    times = [
      row.datetime + '-01 00:00:00',
      row.datetime + '-' + new Date(row.year, row.month + 1, 0).getDate() + ' 23:59:59'
    ]
  }
  ownerStatRef.value.open(queryParams, times, queryParams.tenantId)
}

const exportOwner = async (row) => {
  let times
  if (queryParams.group == 'day') {
    times = [row.datetime + ' 00:00:00', row.datetime + ' 23:59:59']
  } else if (queryParams.group == 'month') {
    times = [
      row.datetime + '-01 00:00:00',
      row.datetime + '-' + new Date(row.year, row.month + 1, 0).getDate() + ' 23:59:59'
    ]
  }

  try {
    // 发起导出
    exportLoading.value = true
    const data = await proxyApi.OwnerexportExcelByProxy({
      group: queryParams.group,
      times: times
    })
    download.excel(data, '坐席数据报表.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}
const getCurrentMonthRange = () => {
  const now = new Date()
  const start = new Date(now.getFullYear(), now.getMonth(), 1) // 当前月的第一天
  const end = new Date(now.getFullYear(), now.getMonth() + 1, 0, 23, 59, 59) // 当前月的最后一天

  // 格式化为 YYYY-MM-DD HH:mm:ss
  const formattedStart = formatDate(start)
  const formattedEnd = formatDate(end)

  return [formattedStart, formattedEnd]
}
const formatDate = (date) => {
  const pad = (num) => (num < 10 ? '0' + num : num)
  return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())} ${pad(
    date.getHours()
  )}:${pad(date.getMinutes())}:${pad(date.getSeconds())}`
}
const customerOptions = ref([])

/**客户列表*/
const getMyCustomer = async () => {
  customerOptions.value = await proxyApi.getProxyCustomer()
}
onMounted(async () => {
  await getMyCustomer()
  queryParams.times = getCurrentMonthRange()
})
</script>

<style lang="scss" scoped></style>
